<script setup lang="ts">
import type { Props, Emits } from './utils/types'
import { ElMessage, ElLoading } from 'element-plus'
import APIInformation from '@/api/information'
import { useAuth } from '@/stores/index'

const dialogVisible = shallowRef(false)
const $props = defineProps<Props>()
const $emit = defineEmits<Emits>()
const { getInfo } = useAuth()


watch($props, (newValue) => {
    dialogVisible.value = newValue.modelValue
}, { immediate: true })

watch(dialogVisible, (newValue) => {
    $emit('update:modelValue', newValue)
})


const username = shallowRef<string>('')

function submitChangeUsername() {
    const test = /^[\u4E00-\u9FA5a-zA-Z0-9]{3,6}$/
    if (!username.value) return ElMessage.error('请输入用户名')
    if (!test.test(username.value)) return ElMessage.error('请输入3-6位不含特殊符号的新用户名')
    const loading = ElLoading.service({ lock: true })
    APIInformation.changePersonal({ username: username.value }).then(({ msg }) => {
        ElMessage.success(msg)
        getInfo()
        onBeforeClose()
    }).finally(() => {
        loading.close()
    })

}

function onBeforeClose() {
    username.value = ''
    dialogVisible.value = false
}

</script>

<template>
    <el-dialog class="edit-username" v-model="dialogVisible" width="800" destroy-on-close :before-close="onBeforeClose"
        :show-close="false">
        <template #header>
            <DialogClose title="修改用户名" @close="onBeforeClose" />
        </template>
        <div class="con">
            <el-input class="input" v-model="username" size="large" placeholder="请输入3-6位不含特殊符号的新用户名" />
            <span class="hint">用户名设置后无法修改。如入住店铺，用户名会作为您的店铺名称对外展示，请知晓；</span>
            <button type="button" class="submit-btn" @click="submitChangeUsername">确认</button>
        </div>
    </el-dialog>
</template>

<style lang="scss" scoped>
.edit-username {
    .con {
        display: flex;
        flex-direction: column;
        padding-bottom: 40px;

        .submit-btn {
            display: block;
            margin: 0 auto;
            margin-top: 42px;
            width: 231px;
            height: 40px;
            border-radius: 5px;
            background-color: rgba(15, 64, 245, 1);
            color: rgba(255, 255, 255, 1);
            font-size: 14px;
            border: none;
            cursor: pointer;
        }

        .input {
            width: 435px;
            margin: 0 auto;
            margin-top: 50px;
        }

        .hint {
            text-align: center;
            display: flex;
            justify-content: center;
            align-items: center;
            color: rgba(148, 148, 148, 1);
            font-size: 14px;
            margin-top: 62px;

            &::before {
                content: '';
                display: block;
                width: 4px;
                height: 14px;
                background-color: rgba(254, 0, 0, 1);
                margin-right: 5px;
            }
        }
    }
}
</style>
